package com.gateway.video.rtsp.server.handler.support;

import com.gateway.video.rtsp.server.VideoServerConstants;
import com.google.common.base.Preconditions;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.rtsp.RtspVersions;
import io.netty.util.concurrent.Promise;
import lombok.var;
import org.kohsuke.MetaInfServices;
import java.time.LocalDateTime;
import java.util.UUID;

@MetaInfServices(RtspRequest.class)
public class SetupRtspRequest extends AbstractRtspRequest {
    @Override
    protected void doHanlder(ChannelHandlerContext ctx, HttpRequest request, Promise promise) {
        var response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, HttpResponseStatus.OK);
        response.headers().set(HttpHeaderNames.SERVER, VideoServerConstants.VIDEO_VERSION);
        response.headers().set(HttpHeaderNames.DATE, LocalDateTime.now());
        /* RTCP主要是为其服务提供质量 RTP用来传输数据 */
        response.headers().set(VideoServerConstants.TRANSPORT, buildTransport(request));
        /* TODO 会话信息带上连接超时 */
        response.headers().set(VideoServerConstants.SESSION, UUID.randomUUID());
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache");
        response.headers().set(VideoServerConstants.CSEQ, request.headers().get(VideoServerConstants.CSEQ));

        ctx.writeAndFlush(response, ctx.newPromise().addListener(future -> {
            if(future.isSuccess()) {
                promise.setSuccess(response);
            }else {
                promise.setFailure(future.cause());
            }
        }));
    }

    @Override
    public boolean isSupport(HttpRequest request) {
        return request.method().name().equals(RtspHttpMethod.SETUP.name());
    }

    private String buildTransport(HttpRequest request) {
        String requestTransport = request.headers().get(VideoServerConstants.TRANSPORT);
        String reponseTransport = requestTransport;

        Preconditions.checkNotNull(requestTransport);

        reponseTransport += ";server_port=" + 12008 + "-" + 12009 + ";mode=play";

        return reponseTransport;
    }
}
